package com.imagefake.config.handler;

import com.alibaba.fastjson2.JSON;
import com.imagefake.vo.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class AppAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.warn("用户登录失败  " + exception.getMessage());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        //返回JSON出去
        HttpResult httpResult = new HttpResult(-1, "登陆失败");
        if (exception instanceof BadCredentialsException) {
            httpResult.setData("密码不正确");
        } else if (exception instanceof DisabledException) {
            httpResult.setData("账号被禁用");
        } else if (exception instanceof UsernameNotFoundException) {
            httpResult.setData("用户名不存在");
        } else if (exception instanceof CredentialsExpiredException) {
            httpResult.setData("密码已过期");
        } else if (exception instanceof AccountExpiredException) {
            httpResult.setData("账号已过期");
        } else if (exception instanceof LockedException) {
            httpResult.setData("账号被锁定");
        } else {
            httpResult.setData("未知异常");
        }
        String httpResultJSON = JSON.toJSONString(httpResult);
        response.getWriter().write(httpResultJSON);
        response.getWriter().flush();

    }
}
